package io.renren.controller;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.entity.ProjectInfoEntity;
import io.renren.service.impl.ProjectInfoServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/project")
@Api(tags = "招采项目接口")
public class ProjectInfoController {

    @Autowired
    private ProjectInfoServiceImpl projectInfoService;

    /**
     * params 中含以下参数
     * limit 每页大小
     * page 页码
     *
     * @return 返回结果
     */
    @PostMapping("list")
    @ApiOperation("获取招采项目列表")
    public R list(@RequestBody Map<String, Object> params) {
        try {

            return R.ok().put("data", projectInfoService.querList(params));
        } catch (Exception e) {
            return R.error(9999, "获取招采项目列表发生异常");
        }
    }

    @Autowired
    RedisUtils redisUtils;

    @PostMapping("get")
    @ApiOperation("获取招采项目列表")
    public R get(Long id) {
        try {
            if (id == null) {
                return R.error("项目编号为空");
            }
            String key = "zc_project_" + id;
            String values = redisUtils.get(key);
            if (!StringUtils.isEmpty(values)) {
                return R.ok().put("data", JSON.parseObject(values, ProjectInfoEntity.class));
            }
            ProjectInfoEntity entity = projectInfoService.getById(id);
            if (entity != null) {
                redisUtils.set(key, JSON.toJSONString(entity), 300);
            }
            return R.ok().put("data", entity);
        } catch (Exception e) {
            return R.error(9999, "获取招采项目列表发生异常");
        }
    }


}
